import React, { useEffect, useMemo, useState } from "react";
import { Drawer, Form, Space, Button, message } from "antd";
import FormRender from '@/components/FormRender';
import { getSessionUser } from '@/utils';
import { statusArr } from '../metaData'
import { addCustomer, editCustomer } from '@/api';

interface Props {
  pageType?: string
  isShow: boolean
  editItem: any
  onCancel: (...agrs: any[]) => void
  onFinish: () => void
  setEditItem: ({ }) => void
}

export default function OperateMemberDrawer({ pageType, isShow, onCancel, editItem = {}, setEditItem, onFinish }: Props) {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false)
  const prefixText = useMemo(() => { return !!editItem?.customerId ? '编辑' : '新增' }, [editItem]);

  useEffect(() => {
    if (isShow && !!editItem?.customerId) {
      form.setFieldsValue(editItem)
    }
  }, [editItem])
  const submit = async () => {
    const values = await form.validateFields();
    if (!values) return;

    const userInfo = getSessionUser();
    let params = { ...values, followUpUserId: pageType !== 'publcCustomer' ? userInfo?.userId : null };
    const requestFn = !!editItem?.customerId ? editCustomer : addCustomer;

    if (editItem?.customerId) {
      params = { ...params, customerId: editItem?.customerId }
    }
    setLoading(true);
    requestFn(params).then((data) => {
      setLoading(false);
      if (!data) return;
      message.success(`${prefixText}成功`);
      onClose();
      onFinish?.();
    })
      .catch((err) => {
        throw (err);
      });
  };

  const onClose = () => {
    form?.resetFields();
    onCancel(null, false);
    setEditItem?.({});
  };

  const formItemList = useMemo(
    () => {
      return [
        {
          title: '',
          Items: [
            {
              label: '客户姓名',
              name: 'customerName',
              type: 'input',
              // initValue: editItem?.customerName,
              rules: [
                { required: true },
                { max: 128, message: '最大长度不超过128' },
              ]
            },
            {
              label: '客户电话',
              name: 'phone',
              type: 'input',
              // initValue: editItem?.phone,
              rules: [
                { required: true },
                {
                  pattern: /^[0-9]+(-[0-9]+)*$/,
                  message: '请输入正确的电话号码'
                },
              ]
            },
            {
              label: '微信号码',
              name: 'weChat',
              type: 'input',
              // initValue: editItem?.weChat,
            },
            {
              label: '年龄',
              name: 'age',
              type: 'input',
              // initValue: editItem?.age,
              rules: [
                { pattern: /^[0-9]{0,3}$/, message: '请输入正确的年龄' }
              ]
            },
            {
              label: '性别',
              name: 'gender',
              type: 'select',
              // initValue: editItem?.gender,
              items: [
                { name: '男', value: 'man' },
                { name: '女', value: 'woman' },
              ],
            },
            {
              label: '身份证号码',
              name: 'identityNumber',
              type: 'input',
              // initValue: editItem?.identityNumber,
              rules: [
                {
                  pattern: /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[\dX]$/,
                  message: '请输入正确的身份证号码'
                }
              ]
            },
            {
              label: '地址',
              name: 'customerAddress',
              type: 'input',
              // initValue: editItem?.customerAddress,
            },
            // {
            //   label: '客户编号',
            //   name: 'customerCode',
            //   type: 'input',
            // },
            {
              label: '贷款额度',
              name: 'loanLimit',
              type: 'input',
              // initValue: editItem?.loanLimit,
              rules: [
                { pattern: /^(?:[0-9]|[1-9]\d{0,11})$/, message: '请输入非负整数' }
              ]
            },
            {
              label: '客户状态',
              name: 'status',
              type: 'select',
              // initValue: editItem?.status,
              items: statusArr,
            },
            {
              label: '客户类型',
              name: 'customerType',
              type: 'select',
              // initValue: editItem?.customerType,
              items: [
                { name: '个人', value: 'personal' },
                { name: '公司', value: 'company' },
              ],
            },
            {
              label: '客户星级',
              name: 'customerRank',
              type: 'select',
              // initValue: editItem?.customerRank,
              items: [
                { name: '无', value: 0 },
                { name: '一星级', value: 1 },
                { name: '二星级', value: 2 },
                { name: '三星级', value: 3 },
                { name: '四星级', value: 4 },
                { name: '五星级', value: 5 },
              ],
            },
          ],
        }
      ]
    }, [editItem]);
  return (
    <Drawer
      maskClosable={false}
      title={`${prefixText}客户`}
      destroyOnClose={true}
      open={isShow}
      width={720}
      onClose={onClose}
      extra={
        <Space>
          <Button onClick={onClose}>关闭</Button>
          <Button onClick={submit} type="primary" loading={loading}>
            提交
          </Button>
        </Space>
      }
    >
      <FormRender
        form={form}
        formItem={formItemList}
      />
    </Drawer>
  );
}